//
//  FriendProfileView.m
//  iTweet
//
//  Created by Dang Duc Nam on 6/4/09.
//  Copyright 2009 Unitech. All rights reserved.
//

#import "FriendProfileView.h"
#import "FriendProfileViewController.h"
#import "User.h"
#import "iTweetAppDelegate.h"
#import <QuartzCore/QuartzCore.h>

@implementation FriendProfileView
@synthesize friendProfile;
@synthesize viewController;
@synthesize followButton;
@synthesize unFollowButton;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code here.
		friendProfile = nil;
		viewController = nil;
		// set the background color of the view to clearn
		self.backgroundColor=[UIColor clearColor];
		appDelegate = (iTweetAppDelegate *)[[UIApplication sharedApplication] delegate];
    }
    return self;
}


+ (CGSize)preferredViewSize {
	return CGSizeMake(256,256);
}

// yes this view can become first responder
- (BOOL)canBecomeFirstResponder {
	return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	
	[viewController flipCurrentView];
	
}

- (void)drawRect:(CGRect)rect {
	
	// get the background image for the state of the element
	// position it appropriately and draw the image
	UIImage *backgroundImage = [friendProfile imageForFriendProfileView];
	CGRect elementSymbolRectangle = CGRectMake(0,0, [backgroundImage size].width, [backgroundImage size].height);
	[backgroundImage drawInRect:elementSymbolRectangle];
	
	// all the text is drawn in white
	[[UIColor whiteColor] set];
	
	// draw the user name
	CGPoint point = CGPointMake(2,256/2-110);
	UIFont *font = [UIFont boldSystemFontOfSize:36];
	CGSize stringSize = [friendProfile.name sizeWithFont:font];

	CGRect nameRectangle = CGRectMake(point.x, point.y, self.bounds.size.width-4, 40);
	UILabel *name = [[UILabel alloc] initWithFrame:nameRectangle];

	name.text = friendProfile.name;
	name.textAlignment = UITextAlignmentCenter;
	[name setTextColor:[UIColor whiteColor]];
	[name setBackgroundColor:[UIColor clearColor]];
	[name setFont:font];
	name.adjustsFontSizeToFitWidth = YES;
	[self addSubview:name];
	
	//[friendProfile.name drawAtPoint:point withFont:font];

	// draw the screen name
	font = [UIFont boldSystemFontOfSize:24];
	stringSize = [friendProfile.screen_name sizeWithFont:font];
	point = CGPointMake((self.bounds.size.width-stringSize.width)/2,256/2-70);
	[friendProfile.screen_name drawAtPoint:point withFont:font];
	
	// draw image
	UIImage *avatarImage = [appDelegate getUserNormalImage:friendProfile];
	avatarImage = [ImageManipulation makeRoundCornerImage:avatarImage : 5 : 5];
	point = CGPointMake((self.bounds.size.width-[avatarImage size].width)/2,256/2-30);
	elementSymbolRectangle = CGRectMake(point.x,point.y, [avatarImage size].width, [avatarImage size].height);
	[avatarImage drawInRect:elementSymbolRectangle];

	CGRect buttonFrame = CGRectMake((self.bounds.size.width-100)/2, point.y+[avatarImage size].width+5, 100.0, 30.0);
	self.followButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	self.followButton.frame=buttonFrame;
	[self.followButton setTitle:NSLocalizedString(@"FollowButtonKey", nil) forState:UIControlStateNormal];
	[self.followButton addTarget:[self viewController] action:@selector(doFollow:) forControlEvents:UIControlEventTouchUpInside];
	
	
	self.unFollowButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	self.unFollowButton.frame=buttonFrame;
	// TODO: NSlocalized
	[self.unFollowButton setTitle:NSLocalizedString(@"UnFollowButtonKey", nil) forState:UIControlStateNormal];
	[self.unFollowButton addTarget:[self viewController] action:@selector(doUnFollow:) forControlEvents:UIControlEventTouchUpInside];
	
	if (friendProfile.following == NO)
		[self addSubview:self.followButton];
	else
		[self addSubview:self.unFollowButton];
	// draw description
	font = [UIFont boldSystemFontOfSize:14];
	point = CGPointMake(2,256/2+50);
	CGRect descriptionRectangle = CGRectMake(point.x, point.y, self.bounds.size.width-4, 80);
	UILabel *description = [[UILabel alloc] initWithFrame:descriptionRectangle];
	description.text = friendProfile.description;
	description.numberOfLines = 0;
	description.textAlignment = UITextAlignmentCenter;
	[description setTextColor:[UIColor whiteColor]];
	description.lineBreakMode = UILineBreakModeWordWrap;
	[description setBackgroundColor:[UIColor clearColor]];
	[description setFont:font];
	[self addSubview:description];
}

CGImageRef AEViewCreateGradientImage (int pixelsWide,
									  int pixelsHigh)
{
	CGImageRef theCGImage = NULL;
    CGContextRef gradientBitmapContext = NULL;
    CGColorSpaceRef colorSpace;
	CGGradientRef grayScaleGradient;
	CGPoint gradientStartPoint, gradientEndPoint;
	
	// Our gradient is always black-white and the mask
	// must be in the gray colorspace
    colorSpace = CGColorSpaceCreateDeviceGray();
	
	// create the bitmap context
    gradientBitmapContext = CGBitmapContextCreate (NULL, pixelsWide, pixelsHigh,
												   8, 0, colorSpace, kCGImageAlphaNone);
	
	if (gradientBitmapContext != NULL) {
		// define the start and end grayscale values (with the alpha, even though
		// our bitmap context doesn't support alpha the gradient requires it)
		CGFloat colors[] = {0.0, 1.0,1.0, 1.0,};
		
		// create the CGGradient and then release the gray color space
		grayScaleGradient = CGGradientCreateWithColorComponents(colorSpace, colors, NULL, 2);
		
		// create the start and end points for the gradient vector (straight down)
		gradientStartPoint = CGPointZero;
		gradientEndPoint = CGPointMake(0,pixelsHigh);
		
		// draw the gradient into the gray bitmap context
		CGContextDrawLinearGradient (gradientBitmapContext, grayScaleGradient, gradientStartPoint, gradientEndPoint, kCGGradientDrawsAfterEndLocation);
		
		// clean up the gradient
		CGGradientRelease(grayScaleGradient);
		
		// convert the context into a CGImageRef and release the
		// context
		theCGImage=CGBitmapContextCreateImage(gradientBitmapContext);
		CGContextRelease(gradientBitmapContext);
		
	}
	
	// clean up the colorspace
	CGColorSpaceRelease(colorSpace);
	
	// return the imageref containing the gradient
    return theCGImage;
}




- (UIImage *)reflectedImageRepresentationWithHeight:(NSUInteger)height
{
	CGContextRef mainViewContentContext;
    CGColorSpaceRef colorSpace;
	
    colorSpace = CGColorSpaceCreateDeviceRGB();
	
	// create a bitmap graphics context the size of the image
    mainViewContentContext = CGBitmapContextCreate (NULL, self.bounds.size.width,height, 8,0, colorSpace, kCGImageAlphaPremultipliedLast);
	
	// free the rgb colorspace
    CGColorSpaceRelease(colorSpace);	
	
	if (mainViewContentContext==NULL)
		return NULL;
	
	// offset the context. This is necessary because, by default, the  layer created by a view for
	// caching its content is flipped. But when you actually access the layer content and have
	// it rendered it is inverted. Since we're only creating a context the size of our 
	// reflection view (a fraction of the size of the main view) we have to translate the context the
	// delta in size, render it, and then translate back (we could have saved/restored the graphics 
	// state
	
	CGFloat translateVertical=self.bounds.size.height-height;
	CGContextTranslateCTM(mainViewContentContext,0,-translateVertical);
	
	// render the layer into the bitmap context
	[self.layer renderInContext:mainViewContentContext];
	
	// translate the context back
	CGContextTranslateCTM(mainViewContentContext,0,translateVertical);
	
	// Create CGImageRef of the main view bitmap content, and then
	// release that bitmap context
	CGImageRef mainViewContentBitmapContext=CGBitmapContextCreateImage(mainViewContentContext);
	CGContextRelease(mainViewContentContext);
	
	// create a 2 bit CGImage containing a gradient that will be used for masking the 
	// main view content to create the 'fade' of the reflection.  The CGImageCreateWithMask
	// function will stretch the bitmap image as required, so we can create a 1 pixel wide
	// gradient
	CGImageRef gradientMaskImage=AEViewCreateGradientImage(1,height);
	
	// Create an image by masking the bitmap of the mainView content with the gradient view
	// then release the  pre-masked content bitmap and the gradient bitmap
	CGImageRef reflectionImage=CGImageCreateWithMask(mainViewContentBitmapContext,gradientMaskImage);
	CGImageRelease(mainViewContentBitmapContext);
	CGImageRelease(gradientMaskImage);
	
	// convert the finished reflection image to a UIImage 
	UIImage *theImage=[UIImage imageWithCGImage:reflectionImage];
	
	// image is retained by the property setting above, so we can 
	// release the original
	CGImageRelease(reflectionImage);
	
	// return the image
	return theImage;
}


- (void)dealloc {
	viewController = nil;
	
	[friendProfile release];
	
    [super dealloc];
}


@end
